﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CSharp_Remote_Control.Enum;
using CSharp_Remote_Control.Model;
using CSharp_Remote_Control.Utils;
using Newtonsoft.Json;


namespace CSharp_Remote_Control.Pages
{
    /// <summary>
    /// Interaction logic for RCBeControl.xaml
    /// </summary>
    public partial class RCBeControl : System.Windows.Controls.UserControl
    {

        class ViewModel : INotifyPropertyChanged
        {
            string? _ip = "127.0.0.1";
            string? _port = "5000";
            string? _deviceCode = "888888";
            string? _deviceCodeConnect = "888888";
            public string? Ip
            {
                get { return _ip; }
                set { _ip = value; OnPropertyChanged("Ip"); }
            }
            public string? Port
            {
                get { return _port; }
                set { _port = value; OnPropertyChanged("Port"); }
            }
            public string? DeviceCode
            {
                get { return _deviceCode; }
                set { _deviceCode = value; OnPropertyChanged("DeviceCode"); }
            }
            public string? DeviceCodeConnect
            {
                get { return _deviceCodeConnect; }
                set { _deviceCodeConnect = value; OnPropertyChanged("DeviceCodeConnect"); }
            }
            protected internal virtual void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
            public event PropertyChangedEventHandler? PropertyChanged;
        }

        ViewModel? VM;
        TCPClient client;

        System.Threading.Timer Timer;

        public RCBeControl()
        {
            InitializeComponent();
            this.VM = new ViewModel();
            this.DataContext = this.VM;
        }


        private void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            client = new TCPClient();
            client.OnClientStartEvent += (string ip, int p) =>
            {
                IPEndPoint? iPEndPoint = (IPEndPoint?)client?.Client?.Client.LocalEndPoint;
                // 建立连接后立刻发送配置信息
                client.SendMsg(MsgUtil.TCPMsgWrapTO(
                    new TransformModel()
                    {
                        IpFrom = iPEndPoint.Address.ToString().Split(":").LastOrDefault(),
                        PortFrom = iPEndPoint.Port,
                        codeFrom = this.VM?.DeviceCode,
                        // codeTo = this.VM?.DeviceCodeConnect,
                        ClientType = EnumState.TCP_CLIENT_BE_CONTROL, // 被控端
                        Type = EnumState.TCP_CONFIG_WHEN_START,
                    }
                    ));
            };
            client.OnServerMsgJsonEvent += (s) =>
            {
                TxtReceive.Dispatcher.BeginInvoke(new Action(() =>
                {
                    TxtReceive.AppendText("服务端回复: " + s + Environment.NewLine);
                }
                ));


                TransformModel? m = JsonConvert.DeserializeObject<TransformModel>(s);
                if (m == null) return;
                switch (m.Type)
                {
                    case EnumState.TCP_CONFIG_CONTROL_BEGIN:
                        // 获取控制端, 被控端编码, 密码, 截图, 发送数据给服务器, 让服务器转发数据
                        string? codeControl = m.codeFrom;
                        string? codeBeControl = m.codeTo;
                        string? pwdBeControl = m.pwdTo;

                        Timer = new System.Threading.Timer(new TimerCallback(delegate
                        {
                            SendImg(codeBeControl, codeControl);
                        }), null, 0, 1000);

                        break;
                    default:
                        break;
                }

            };
            client.Open();
        }

        private void BtnSend_Click(object sender, RoutedEventArgs e)
        {
            TransformModel m = new TransformModel()
            {
                DataBase64 = this.TxtSend.Text,
                Type = Enum.EnumState.TCP_TEXT
            };
            string jsonStr = JsonConvert.SerializeObject(m);
            client.SendMsg(MsgUtil.TCPMsgWrap(jsonStr));
        }

        private void BtnSendImg_Click(object sender, RoutedEventArgs e)
        {
            //SendImg();
        }

        public void SendImg(string? codeFrom, string? codeTo)
        {
            Bitmap bm = ScreenUtil.CaptureScreen();
            long s = BitmapUtil.CalculateBitmapSize(bm);
            Debug.WriteLine($"图片大小 {s / 1024} KB");

            bm = BitmapUtil.ScaleBitmap(bm, 600, 400);
            s = BitmapUtil.CalculateBitmapSize(bm);
            Debug.WriteLine($"缩放图片大小 {s / 1024} KB");

            String? imgBase64 = BitmapUtil.BitmapToBase64(bm, ImageFormat.Png);
            Bitmap bm2 = BitmapUtil.Base64ToBitmap(imgBase64);

            BitmapSource b = ScreenUtil.ConvertBitmapToBitmapSource(bm2);
            ImgScreen.Source = b;

            TransformModel m = new TransformModel()
            {
                DataBase64 = imgBase64,
                Type = EnumState.TCP_IMG,
                codeFrom = codeFrom,
                codeTo = codeTo,
            };

            String jsonStr = JsonConvert.SerializeObject(m);
            // 发送截图数据到控制端
            client.SendMsg(MsgUtil.TCPMsgWrap(jsonStr));
        }
    }
}
